package com.lucifer.treasure;

import com.lucifer.treasure.enchant.effect.SwordAuraEnchantmentEffect;
import com.lucifer.treasure.enchant.effect.SwordAuraPvPSystem;
import com.lucifer.treasure.config.SwordAuraConstants;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.render.RenderTickCounter;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import org.lwjgl.glfw.GLFW;

/**
 * 御剑术客户端按键绑定处理器 + HUD显示系统
 */
public class SwordAuraClientHandler implements ClientModInitializer {
    
    // 按键绑定
    private static KeyBinding swordAuraToggleKey;
    private static KeyBinding testHostilityKey; // 🧪 测试敌对关系按键
    
    // 状态追踪
    private boolean wasKeyPressed = false;
    private boolean wasTestKeyPressed = false; // �� 测试按键状态
    
    // 调试用tick计数器
    private static int clientTickCounter = 0;
    
    // HUD显示相关
    private static boolean showHUD = true;
    private static int hudX = 10; // HUD X坐标
    private static int hudY = 10; // HUD Y坐标
    
    // 拖动相关
    private static boolean isDragging = false;
    private static int dragStartX = 0;
    private static int dragStartY = 0;
    private static int initialHudX = 0;
    private static int initialHudY = 0;
    
    // 🆕 服务端数据缓存
    private static boolean isAuraEnabled = false;
    private static int cachedAuraLevel = 0;
    private static int cachedVisibleSwords = 0;
    private static int cachedHitEffectSwords = 0;
    private static int cachedRecoveringSwords = 0;
    private static int cachedMaxSwords = 0;
    private static int cachedHostilityCount = 0;
    private static long lastStatusRequest = 0;
    private static final long STATUS_REQUEST_INTERVAL = 1000; // 每1秒请求一次状态
    
    @Override
    public void onInitializeClient() {
        // 注册按键绑定
        swordAuraToggleKey = KeyBindingHelper.registerKeyBinding(new KeyBinding(
            "key.lucifer_treasure.sword_aura_toggle", // 翻译键
            InputUtil.Type.KEYSYM, 
            GLFW.GLFW_KEY_R, // R键
            "category.lucifer_treasure.keys" // 按键分类
        ));
        
        // 🧪 注册测试敌对关系按键
        testHostilityKey = KeyBindingHelper.registerKeyBinding(new KeyBinding(
            "key.lucifer_treasure.test_hostility", // 翻译键
            InputUtil.Type.KEYSYM,
            GLFW.GLFW_KEY_H, // H键
            "category.lucifer_treasure.keys" // 按键分类
        ));
        
        System.out.println("🎮 御剑术按键绑定已注册：R键切换御剑术状态");
        
        // 注册客户端tick事件处理器
        ClientTickEvents.END_CLIENT_TICK.register(client -> {
            handleKeyInput(client);
        });
        
        // 🆕 注册客户端御剑术渲染事件 - 每tick调用
        ClientTickEvents.END_CLIENT_TICK.register(client -> {
            if (client.player != null && client.world != null) {
                // 🧪 调试：确认客户端tick事件被触发（每100tick打印一次避免刷屏）
                if (++clientTickCounter % 100 == 0) {
                    // System.out.println("🧪 [客户端Tick] 客户端tick事件正常触发，tick: " + clientTickCounter);
                }
                
                // 🆕 定期请求服务端状态数据（用于HUD）
                requestServerStatus(client);
                
                // 调用御剑术客户端渲染逻辑
                try {
                    // 获取御剑术等级
                    int auraLevel = com.lucifer.treasure.enchant.effect.SwordAuraEnchantmentEffect.getPlayerSwordAuraLevel(client.player);
                    
                    // 🆕 更新客户端等级缓存
                    com.lucifer.treasure.util.SwordAuraRenderer.setClientAuraLevel(client.player.getUuid(), auraLevel);
                    
                    // 检查御剑术是否开启
                    boolean auraEnabled = com.lucifer.treasure.enchant.effect.SwordAuraEnchantmentEffect.isAuraEnabled(client.player.getUuid());
                    
                    // 只有当御剑术开启且等级大于0时才进行渲染
                    if (auraEnabled && auraLevel > 0) {
                        // 🎯 调用共享渲染器 - 和服务端使用相同逻辑
                        SwordAuraClientRenderer.renderClientSwordAura(client.player, client.world, auraLevel);
                    }
                } catch (Exception e) {
                    // 如果渲染失败，不要频繁打印错误日志
                    if (clientTickCounter % 1000 == 0) {
                        System.err.println("❌ [客户端Tick] 御剑术客户端渲染失败: " + e.getMessage());
                    }
                }
            }
        });
        
        // 注册HUD渲染器
        HudRenderCallback.EVENT.register(this::renderSwordAuraHUD);
        
        // 🆕 注册网络包接收器
        com.lucifer.treasure.network.SwordAuraHUDClientHandler.register();
        
        System.out.println("🎮 御剑术HUD显示系统已启用");
    }
    
    /**
     * 处理按键输入
     */
    private void handleKeyInput(MinecraftClient client) {
        PlayerEntity player = client.player;
        if (player == null) return;
        
        // 处理御剑术切换按键
        boolean keyPressed = swordAuraToggleKey.isPressed();
        
        // 检测按键状态变化（从未按下到按下）
        if (keyPressed && !wasKeyPressed) {
            // 检查是否有御剑术附魔（支持主手和副手）
            int auraLevel = SwordAuraEnchantmentEffect.getPlayerSwordAuraLevel(player);
            if (auraLevel > 0) {
                // 🔧 区分单机和多人游戏模式
                if (client.getServer() != null) {
                    // 🎯 单机模式：直接调用服务端方法
                    boolean beforeToggle = SwordAuraEnchantmentEffect.isAuraEnabled(player.getUuid());
                    System.out.println("🎮 [单机模式] 切换前状态: " + (beforeToggle ? "开启" : "关闭"));
                    
                // 切换御剑术状态
                SwordAuraEnchantmentEffect.toggleAuraFromClient(player);
                    
                    // 🧪 验证切换是否成功
                    boolean afterToggle = SwordAuraEnchantmentEffect.isAuraEnabled(player.getUuid());
                    System.out.println("🎮 [单机模式] 切换后状态: " + (afterToggle ? "开启" : "关闭"));
                    System.out.println("🎮 [单机模式] 状态切换" + (beforeToggle != afterToggle ? "成功" : "失败"));
                    
                    // 发送消息给玩家确认
                    if (client.currentScreen == null) {
                        String statusText = afterToggle ? "§a开启" : "§c关闭";
                        player.sendMessage(net.minecraft.text.Text.literal("§b[御剑术]已" + statusText), true);
                    }
                } else {
                    // 🎯 多人游戏模式：发送聊天命令给服务端
                    System.out.println("🎮 [多人游戏] 向服务端发送切换命令");
                    
                    // 发送聊天命令到服务端
                    if (client.getNetworkHandler() != null) {
                        String command = "/sword_aura_toggle";
                        client.getNetworkHandler().sendChatCommand(command.substring(1)); // 去掉斜杠
                        System.out.println("🎮 [多人游戏] 已发送命令: " + command);
                    } else {
                        System.err.println("❌ [多人游戏] 无法发送命令：网络处理器为空");
                    }
                }
            } else {
                // 没有御剑术附魔，显示提示
                if (client.currentScreen == null) { // 只在游戏界面显示消息
                    player.sendMessage(net.minecraft.text.Text.literal("§c需要装备有御剑术附魔的武器！"), true);
                }
                System.out.println("⚠️ [客户端] 需要御剑术附魔武器");
            }
        }
        
        wasKeyPressed = keyPressed;
        
        // 🧪 处理测试敌对关系按键
        boolean testKeyPressed = testHostilityKey.isPressed();
        
        if (testKeyPressed && !wasTestKeyPressed) {
            System.out.println("🧪 [客户端] 开始创建测试敌对关系...");
            
            // 🧪 创建测试敌对关系
            SwordAuraEnchantmentEffect.createTestHostilities(player);
            
            // 立即检查是否创建成功
            java.util.List<SwordAuraPvPSystem.HostilityInfo> testCheck = SwordAuraEnchantmentEffect.getPlayerHostilities(player);
            System.out.println("🧪 [客户端] 创建后检查: " + (testCheck != null ? testCheck.size() : 0) + " 个敌对关系");
            
            if (client.currentScreen == null) {
                player.sendMessage(net.minecraft.text.Text.literal("§a🧪 已创建测试敌对关系！按F9再次创建新的测试数据"), true);
            }
            System.out.println("🧪 [客户端] 检测到F9键按下，创建测试敌对关系");
        }
        
        wasTestKeyPressed = testKeyPressed;
    }
    
    /**
     * 🎮 渲染御剑术HUD显示 - 扁平化设计，分离显示
     */
    private void renderSwordAuraHUD(DrawContext context, RenderTickCounter tickCounter) {
        MinecraftClient client = MinecraftClient.getInstance();
        if (client.player == null || client.world == null || !showHUD) {
            return;
        }
        
        PlayerEntity player = client.player;
        
        // 🔧 修复：总是显示HUD，让用户知道御剑术状态
        // 🆕 优先使用缓存的服务端数据，如果没有则使用本地数据作为后备
        int auraLevel = cachedAuraLevel > 0 ? cachedAuraLevel : SwordAuraEnchantmentEffect.getPlayerSwordAuraLevel(player);
        boolean isEnabled = (cachedAuraLevel > 0) ? isAuraEnabled : SwordAuraEnchantmentEffect.isAuraEnabled(player.getUuid());
        
        // 🆕 更新客户端等级缓存
        com.lucifer.treasure.util.SwordAuraRenderer.setClientAuraLevel(player.getUuid(), auraLevel);
        
        // 如果没有御剑术等级但开启了，显示提示状态
        if (auraLevel <= 0 && isEnabled) {
            // 显示简化的HUD，提示需要装备武器
            renderSimpleStatusHUD(context, client, "§c需要御剑术附魔武器", "§7已开启但无武器");
            return;
        }
        
        // 如果御剑术关闭，显示关闭状态
        if (!isEnabled) {
            if (auraLevel > 0) {
                // 有武器但关闭了
                renderSimpleStatusHUD(context, client, "§7御剑术已关闭", String.format("§7等级:%d (按%s开启)", auraLevel, 
                    swordAuraToggleKey.getBoundKeyLocalizedText().getString()));
            } else {
                // 没有武器且关闭了
                renderSimpleStatusHUD(context, client, "§7御剑术已关闭", "§7无御剑术附魔武器");
            }
            return;
        }
        
        // 🎯 正常显示完整HUD（御剑术开启且有武器）
        
        // 🆕 优先使用缓存的服务端数据，如果没有则使用本地数据作为后备
        int visibleSwords, hitEffectSwords, recoveringSwords;
        
        if (cachedAuraLevel > 0) {
            // 使用缓存的服务端数据
            visibleSwords = cachedVisibleSwords;
            hitEffectSwords = cachedHitEffectSwords;
            recoveringSwords = cachedRecoveringSwords;
        } else {
            // 使用本地数据作为后备
            visibleSwords = SwordAuraClientRenderer.getClientVisibleSwordCount(player.getUuid());
            hitEffectSwords = SwordAuraClientRenderer.getClientHitEffectSwordCount(player.getUuid());
            recoveringSwords = SwordAuraClientRenderer.getClientRecoveringSwordCount(player.getUuid());
        }
        
        // 🧪 调试信息：输出获取到的数据
        // System.out.println("🧪 [HUD] 获取数据 - 可见剑:" + visibleSwords + " 攻击剑:" + hitEffectSwords + " 恢复剑:" + recoveringSwords);
        
        // 🆕 获取敌对关系信息（优先使用缓存数据）
        java.util.List<SwordAuraPvPSystem.HostilityInfo> allHostilities;
        
        if (cachedAuraLevel > 0) {
            // 如果有缓存数据，创建虚拟敌对关系列表以显示数量
            allHostilities = new java.util.ArrayList<>();
            for (int i = 0; i < cachedHostilityCount; i++) {
                // 创建虚拟敌对关系条目用于UI显示
                allHostilities.add(new SwordAuraPvPSystem.HostilityInfo("敌对玩家" + (i + 1), 60 * 20, true)); // 60秒虚拟时间（以tick为单位）
            }
        } else {
            // 使用本地数据作为后备
            allHostilities = SwordAuraEnchantmentEffect.getPlayerHostilities(player);
        }
        
        // 🧪 调试信息：输出获取到的敌对关系数量
        if (allHostilities != null && !allHostilities.isEmpty()) {
            // System.out.println("🧪 [客户端HUD] 获取到 " + allHostilities.size() + " 个敌对关系");
            // for (SwordAuraPvPSystem.HostilityInfo info : allHostilities) {
            //     System.out.println("  - " + info.playerName + " (" + info.getRemainingSeconds() + "s)");
            // }
        } else {
            // System.out.println("🧪 [客户端HUD] 未获取到敌对关系数据");
        }
        
        // 🎯 限制显示数量，避免HUD过长
        final int MAX_HOSTILITY_DISPLAY = 3; // 最多显示3个敌对关系（更适合测试）
        java.util.List<SwordAuraPvPSystem.HostilityInfo> hostilities;
        boolean hasMoreHostilities = false;
        
        if (allHostilities.size() > MAX_HOSTILITY_DISPLAY) {
            // 优先显示剩余时间最长的敌对关系
            hostilities = allHostilities.stream()
                    .sorted((h1, h2) -> Long.compare(h2.remainingTicks, h1.remainingTicks))
                    .limit(MAX_HOSTILITY_DISPLAY)
                    .collect(java.util.stream.Collectors.toList());
            hasMoreHostilities = true;
        } else {
            hostilities = allHostilities;
        }
        
        TextRenderer textRenderer = client.textRenderer;
        
        // 🎯 计算HUD尺寸 - 紧凑布局设计
        int maxDisplay = SwordAuraConstants.calculateSwordCount(auraLevel);
        int dotsPerRow = SwordAuraConstants.HUD_DOTS_PER_ROW;
        int rows = (maxDisplay + dotsPerRow - 1) / dotsPerRow; // 向上取整
        int dotSize = SwordAuraConstants.HUD_DOT_SIZE;
        int dotSpacing = SwordAuraConstants.HUD_DOT_SPACING;
        int padding = SwordAuraConstants.HUD_PADDING;
        
        // 计算各部分文字宽度 - 简化标题
        String titleText = String.format("⚔御剑术%d", auraLevel); // 保留"术"字
        // 动态获取当前绑定的键位名称
        String keyName = swordAuraToggleKey.getBoundKeyLocalizedText().getString();
        String controlText = keyName + "切换|拖动"; // 使用动态键位名称
        String controlLine = toRoman(auraLevel) + " " + controlText; // 罗马数字在前，控制提示在后
        int titleWidth = textRenderer.getWidth(titleText);
        int controlLineWidth = textRenderer.getWidth(controlLine);
        
        // 🆕 计算敌对关系显示需要的高度
        int hostilityHeight = 0;
        if (!hostilities.isEmpty()) {
            hostilityHeight = 12 + hostilities.size() * 12; // 标题12px + 每个敌对关系12px
            if (hasMoreHostilities) {
                hostilityHeight += 12; // 为"更多..."行预留空间
            }
        }
        
        // 🎨 精确宽度计算 - 去掉所有浪费的空间
        int minWidthForDots = dotsPerRow * dotSpacing + padding * 2;
        int minWidthForText = Math.max(titleWidth, controlLineWidth) + padding * 2;
        
        // 🆕 考虑敌对关系显示的最小宽度
        int minWidthForHostility = 0;
        if (!hostilities.isEmpty()) {
            for (SwordAuraPvPSystem.HostilityInfo hostility : hostilities) {
                String hostilityText = hostility.playerName; // 移除方向图标
                int hostilityTextWidth = textRenderer.getWidth(hostilityText) + 50; // 50px留给状态条
                minWidthForHostility = Math.max(minWidthForHostility, hostilityTextWidth + padding * 2);
            }
        }
        
        int bgWidth = Math.max(Math.max(minWidthForText, minWidthForDots), minWidthForHostility); // 精确宽度，不设最小值
        int bgHeight = SwordAuraConstants.HUD_BASE_HEIGHT + rows * (dotSize + 1) + hostilityHeight; // 🆕 包含敌对关系高度
        
        // 处理拖动
        handleMouseDrag(client, bgWidth, bgHeight);
        
        // 🎨 扁平化设计 - 现代UI风格
        int bgColor = isDragging ? 0xE0202020 : 0xD0202020; // 深灰色背景
        int accentColor = isDragging ? 0xFF00D4AA : 0xFF00B4D8; // 青色强调色
        
        // 绘制背景卡片 - 无阴影的扁平设计
        context.fill(hudX, hudY, hudX + bgWidth, hudY + bgHeight, bgColor);
        
        // 顶部强调条
        context.fill(hudX, hudY, hudX + bgWidth, hudY + 2, accentColor);
        
        // 📊 标题区域 - 阿拉伯数字 + 罗马数字（第一行）
        context.drawText(textRenderer, Text.literal(titleText).formatted(Formatting.WHITE, Formatting.BOLD), 
                        hudX + padding, hudY + 4, 0xFFFFFF, false);
        
        // 📋 控制提示 - 第二行显示，避免重叠
        context.drawText(textRenderer, Text.literal(controlLine).formatted(Formatting.DARK_GRAY), 
                        hudX + padding, hudY + 14, 0x888888, false);
        
        // 🎯 渲染状态行 - 可见剑数 + 恢复剑数（第三行）
        String renderLine = String.format("渲染: %d/%d", visibleSwords, maxDisplay);
        if (recoveringSwords > 0) {
            renderLine += String.format(" (恢复:%d)", recoveringSwords);
        }
        int renderColor = visibleSwords == maxDisplay ? 0x4AE54A : // 满剑：亮绿色
                         visibleSwords > 0 ? 0xFFA500 : 0xFF4444;  // 部分：橙色，无剑：红色
        
        context.drawText(textRenderer, Text.literal(renderLine), 
                        hudX + padding, hudY + 24, renderColor, false);
        
        // ⚔️ 攻击状态行 - 单独显示（第四行）
        int nextLineY = hudY + 34; // 下一行的基准位置 - 减少间距
        if (hitEffectSwords > 0) {
            String attackLine = String.format("攻击: %d把剑", hitEffectSwords);
            context.drawText(textRenderer, Text.literal(attackLine), 
                            hudX + padding, nextLineY, 0xFFFF44, false); // 黄色攻击状态
            nextLineY += 10; // 有攻击行时，绿点下移 - 减小间距
        }
        
        // 🟢 绿点可视化状态 - 动态位置
        int indicatorY = nextLineY + 2; // 根据是否有攻击行调整位置 - 减小间距
        
        for (int i = 0; i < maxDisplay; i++) {
            int row = i / dotsPerRow;
            int col = i % dotsPerRow;
            int dotX = hudX + padding + col * dotSpacing;
            int dotY = indicatorY + row * (dotSize + 1); // 减小行间距
            
            // 根据剑的状态设置颜色和样式
            int dotColor;
            if (i < visibleSwords) {
                dotColor = 0xFF4AE54A; // 亮绿色：可见剑
            } else if (i < visibleSwords + recoveringSwords) {
                dotColor = 0xFFFF8C00; // 橙色：恢复中
            } else {
                dotColor = 0xFF404040; // 深灰色：无剑
            }
            
            // 绘制圆形点 - 更精美的设计
            context.fill(dotX, dotY, dotX + dotSize, dotY + dotSize, dotColor);
            
            // 添加微妙的边框效果（简化版）
            if (i < visibleSwords + recoveringSwords) {
                context.drawBorder(dotX, dotY, dotSize, dotSize, 0x60FFFFFF);
            }
        }
        
        // 🆕 敌对关系显示区域
        if (!hostilities.isEmpty()) {
            int hostilityStartY = indicatorY + rows * (dotSize + 1) + 8; // 在状态点下方留出间距
            
            // 分隔线
            context.fill(hudX + padding, hostilityStartY, hudX + bgWidth - padding, hostilityStartY + 1, 0xFF444444);
            
            // 敌对关系标题
            String hostilityTitle = String.format("⚔敌对关系 (%d)", allHostilities.size()); // 显示总数，不是显示数
            context.drawText(textRenderer, Text.literal(hostilityTitle).formatted(Formatting.RED, Formatting.BOLD), 
                            hudX + padding, hostilityStartY + 4, 0xFF4444, false);
            
            // 显示每个敌对关系
            int currentHostilityY = hostilityStartY + 16;
            for (SwordAuraPvPSystem.HostilityInfo hostility : hostilities) {
                // 敌对关系状态文字 - 移除方向图标
                String statusText = hostility.playerName;
                String timeText = hostility.getRemainingSeconds() + "s";
                
                // 统一使用红色显示敌对关系
                int statusColor = 0xFFFF6666; // 统一红色
                
                // 绘制状态文字
                context.drawText(textRenderer, Text.literal(statusText), 
                                hudX + padding, currentHostilityY, statusColor, false);
                
                // 绘制剩余时间
                int timeTextWidth = textRenderer.getWidth(timeText);
                context.drawText(textRenderer, Text.literal(timeText), 
                                hudX + bgWidth - padding - timeTextWidth, currentHostilityY, 0xFFAAAAA, false);
                
                // 状态条背景
                int barX = hudX + padding + textRenderer.getWidth(statusText) + 8;
                int barY = currentHostilityY + 2;
                int barWidth = bgWidth - padding * 2 - textRenderer.getWidth(statusText) - timeTextWidth - 16;
                int barHeight = 6;
                
                // 绘制状态条背景
                context.fill(barX, barY, barX + barWidth, barY + barHeight, 0xFF333333);
                
                // 绘制状态条前景（根据剩余时间）
                float progress = hostility.getProgressPercent();
                int progressWidth = (int) (barWidth * progress);
                int progressColor = progress > 0.66f ? 0xFF4AE54A : // 绿色：时间充足
                                   progress > 0.33f ? 0xFFFFAA00 : // 橙色：时间较少  
                                   0xFFFF4444; // 红色：时间不多
                
                if (progressWidth > 0) {
                    context.fill(barX, barY, barX + progressWidth, barY + barHeight, progressColor);
                }
                
                currentHostilityY += 12; // 下一行
            }
            
            // 🆕 显示"更多..."提示
            if (hasMoreHostilities) {
                String moreText = String.format("...还有%d个", allHostilities.size() - hostilities.size());
                context.drawText(textRenderer, Text.literal(moreText).formatted(Formatting.GRAY, Formatting.ITALIC), 
                                hudX + padding, currentHostilityY, 0xFF888888, false);
            }
        }
    }
    
    /**
     * 渲染简单状态HUD
     */
    private void renderSimpleStatusHUD(DrawContext context, MinecraftClient client, String title, String message) {
        TextRenderer textRenderer = client.textRenderer;
        int padding = 8;
        
        // 计算所需宽度
        int titleWidth = textRenderer.getWidth(title);
        int messageWidth = textRenderer.getWidth(message);
        int bgWidth = Math.max(titleWidth, messageWidth) + padding * 2;
        int bgHeight = textRenderer.fontHeight * 2 + padding * 2 + 2; // 两行文字 + 间距
        
        // 处理拖动
        handleMouseDrag(client, bgWidth, bgHeight);
        
        // 绘制背景
        int bgColor = 0xD0202020; // 深灰色背景
        int accentColor = 0xFF00D4AA; // 青色强调色
        
        context.fill(hudX, hudY, hudX + bgWidth, hudY + bgHeight, bgColor);
        context.fill(hudX, hudY, hudX + bgWidth, hudY + 2, accentColor);
        
        // 绘制文字
        context.drawText(textRenderer, Text.literal(title).formatted(Formatting.WHITE, Formatting.BOLD), 
                        hudX + padding, hudY + padding, 0xFFFFFF, false);
        context.drawText(textRenderer, Text.literal(message).formatted(Formatting.DARK_GRAY), 
                        hudX + padding, hudY + padding + textRenderer.fontHeight + 2, 0x888888, false);
    }
    
    /**
     * 转换阿拉伯数字为罗马数字
     */
    private String toRoman(int number) {
        if (number <= 0 || number > 50) return String.valueOf(number); // 超出范围直接返回数字
        
        String[] values = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X",
                          "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX",
                          "XXI", "XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII", "XXVIII", "XXIX", "XXX",
                          "XXXI", "XXXII", "XXXIII", "XXXIV", "XXXV", "XXXVI", "XXXVII", "XXXVIII", "XXXIX", "XL",
                          "XLI", "XLII", "XLIII", "XLIV", "XLV", "XLVI", "XLVII", "XLVIII", "XLIX", "L"};
        
        return values[number];
    }
    
    /**
     * 处理鼠标拖动 - 修复版本
     */
    private void handleMouseDrag(MinecraftClient client, int bgWidth, int bgHeight) {
        if (client.mouse == null) return;
        
        double mouseX = client.mouse.getX() * client.getWindow().getScaledWidth() / client.getWindow().getWidth();
        double mouseY = client.mouse.getY() * client.getWindow().getScaledHeight() / client.getWindow().getHeight();
        
        // 使用正确的鼠标按键检测
        boolean mousePressed = GLFW.glfwGetMouseButton(client.getWindow().getHandle(), GLFW.GLFW_MOUSE_BUTTON_LEFT) == GLFW.GLFW_PRESS;
        
        // 检查鼠标是否在HUD区域内
        boolean mouseInHUD = mouseX >= hudX && mouseX <= hudX + bgWidth && 
                           mouseY >= hudY && mouseY <= hudY + bgHeight;
        
        if (mousePressed && mouseInHUD && !isDragging) {
            // 开始拖动
            isDragging = true;
            dragStartX = (int) mouseX;
            dragStartY = (int) mouseY;
            initialHudX = hudX;
            initialHudY = hudY;
        } else if (!mousePressed && isDragging) {
            // 结束拖动
            isDragging = false;
        } else if (isDragging) {
            // 拖动中 - 实时更新位置
            int deltaX = (int) mouseX - dragStartX;
            int deltaY = (int) mouseY - dragStartY;
            hudX = Math.max(0, Math.min(client.getWindow().getScaledWidth() - bgWidth, initialHudX + deltaX));
            hudY = Math.max(0, Math.min(client.getWindow().getScaledHeight() - bgHeight, initialHudY + deltaY));
        }
    }
    
    /**
     * 获取按键绑定（用于调试）
     */
    public static KeyBinding getSwordAuraToggleKey() {
        return swordAuraToggleKey;
    }
    
    /**
     * 切换HUD显示状态
     */
    public static void toggleHUD() {
        showHUD = !showHUD;
        System.out.println("🎮 御剑术HUD显示: " + (showHUD ? "开启" : "关闭"));
    }
    
    /**
     * 设置HUD位置
     */
    public static void setHUDPosition(int x, int y) {
        hudX = x;
        hudY = y;
    }
    
    /**
     * 🆕 通过网络包更新HUD数据（替代parseHUDData）
     */
    public static void updateHUDData(boolean enabled, int auraLevel, int visibleSwords, 
                                   int hitEffectSwords, int recoveringSwords, int maxSwords, int hostilityCount) {
        try {
            isAuraEnabled = enabled;
            cachedAuraLevel = auraLevel;
            cachedVisibleSwords = visibleSwords;
            cachedHitEffectSwords = hitEffectSwords;
            cachedRecoveringSwords = recoveringSwords;
            cachedMaxSwords = maxSwords;
            cachedHostilityCount = hostilityCount;
            
            // 调试输出
            // System.out.println("🌐 [HUD网络包] 服务端数据更新: 开启=" + isAuraEnabled + 
            //                  " 等级=" + cachedAuraLevel + " 可见剑=" + cachedVisibleSwords + "/" + cachedMaxSwords);
        } catch (Exception e) {
            System.err.println("❌ [HUD网络包] 数据更新失败: " + e.getMessage());
        }
    }
    
    /**
     * 🆕 请求服务端状态数据（用于HUD显示）
     */
    private static void requestServerStatus(MinecraftClient client) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastStatusRequest > STATUS_REQUEST_INTERVAL) {
            lastStatusRequest = currentTime;
            
            if (client.player != null) {
                // 检查是否在多人游戏中
                if (client.getServer() == null) {
                    // 多人游戏 - 发送命令到服务端
                    String command = "/sword_aura_status";
                    client.player.networkHandler.sendCommand(command.substring(1)); // 去掉前缀"/"
                } else {
                    // 单机模式 - 直接调用服务端方法（暂时保留原来的逻辑）
                    // 在单机模式下可以直接访问服务端数据，但为了统一，我们也使用命令
                    String command = "/sword_aura_status";
                    client.player.networkHandler.sendCommand(command.substring(1));
                }
            }
        }
    }
} 